// pages/cart/index/index.js
import { Api } from "../../../utils/api.js"
import { Http } from '../../../utils/http.js'
import { AccurateMath } from "../../../utils/accurateMath.js";
let http = new Http()
let accurateMath = new AccurateMath();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userToken: '',
    userCarts: [],
    goods: [],
    amount: 0,
    selectAll: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAllGoods()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var userToken = getApp().globalData.userToken
    if (userToken.length > 0) {
      this.setData({
        userToken: userToken
      })
      this.getCartGoods()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 自定义方法
   */
  getCartGoods: function () {
    var that = this
    http.sendHttp(Api.get_cart_goods, {
      data: { },
      success: function (res) {
        var userCarts = res.data.obj.userCarts
        if (userCarts.length > 0) {
          var oldCarts = that.data.userCarts
          userCarts.forEach((cart) => {
            if (cart.goods.isShelf == 1 && cart.goods.tbStatus == 1 && cart.goods.stock > cart.goods.sold) {
              cart.canCheck = 1
              cart.priceAmount = accurateMath.accMul(cart.goods.priceSell, cart.number)
              if (oldCarts != null) {
                //恢复选中状态
                oldCarts.forEach((item) => {
                  if (cart.id == item.id) {
                    cart.checked = item.checked
                  }
                })
              }
            } else {
              cart.canCheck = 0
            }
          })
        }
        that.setData({
          userCarts: userCarts
        })
        that.setAmount()
      }
    })
  },

  getAllGoods: function () {
    var that = this
    http.sendHttp(Api.get_all_goods, {
      data: {
        pageNum: 1,
        pageSize: 6
      },
      success: function (res) {
        that.setData({
          goods: res.data.obj.goods
        })
      }
    })
  },

  deleteCart: function(event) {
    var that = this
    wx.showModal({
      title: '提示',
      content: '是否确定删除商品？',
      success: function (res) {
        if (res.confirm) {
          var index = event.currentTarget.dataset['idx']
          var cartId = that.data.userCarts[index].id
          http.sendHttp(Api.del_goods, {
            data: {
              cartIds: cartId
            },
            success: function () {
              var userCarts = that.data.userCarts
              userCarts.splice(index, 1)
              that.setData({
                userCarts: userCarts
              })
            }
          }, "POST")
          this.setAmount()
        }
      }
    })
  },

  setCartNumber: function(number, cartId, index){
    var that = this
    http.sendHttp(Api.update_goods_number, {
      data: {
        cartId: cartId,
        number: number
      },
      success: function(){
        that.setData({
          [`userCarts[${index}].number`]: number,
          [`userCarts[${index}].priceAmount`]: accurateMath.accMul(number, that.data.userCarts[index].goods.priceSell)
        })
        that.setAmount()
      }
    }, "POST")
  },

  setAmount: function(){
    //修改结束金额
    var amount = 0
    if(this.data.userCarts.length > 0){
      this.data.userCarts.forEach(item => {
        if(item.checked){
          amount = accurateMath.accAdd(item.priceAmount, amount)
        }
      })
    }
    this.setData({
      amount: amount
    })
  },

  decreaseCart: function(event){
    var index = event.currentTarget.dataset['idx']
    var cartId = this.data.userCarts[index].id
    var number = this.data.userCarts[index].number
    if(number > 1){
      number -= 1
      this.setCartNumber(number, cartId, index)
    }
  },

  increaseCart: function(event){
    var index = event.currentTarget.dataset['idx']
    var cartId = this.data.userCarts[index].id
    var number = this.data.userCarts[index].number
    number += 1
    this.setCartNumber(number, cartId, index)
  },

  checkCart: function(event){
    var index = event.currentTarget.dataset['idx']
    var userCarts = this.data.userCarts
    userCarts[index].checked = !userCarts[index].checked
    this.setData({
      userCarts: userCarts,
      selectAll: false
    })
    this.setAmount()
  },

  goMallIndex: function () {
    wx.switchTab({
      url: '/pages/mall/index/index',
    })
  },

  goLogin: function () {
    wx.navigateTo({
      url: '/pages/system/login/login',
    })
  },

  selectAll: function(){
    var selectAll = !this.data.selectAll
    var userCarts = this.data.userCarts
    userCarts.forEach( item => {
      if (item.goods.stock > item.goods.sold && item.goods.isShelf == 1 && item.goods.tbStatus == 1) {
        item.checked = selectAll
      }
    })
    this.setData({
      userCarts: userCarts,
      selectAll: selectAll
    })
    this.setAmount()
  },

  goPay: function () {
    var obj = []
    if(this.data.userCarts.length > 0){
      this.data.userCarts.forEach(item => {
        if(item.checked){
          obj.push(item)
        }
      })
    }
    if(obj.length > 0){
      wx.navigateTo({
        url: '/pages/mall/pay/pay?orderList=' + JSON.stringify(obj)
      })
    }else{
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      })
    }
  },

  goGoods: function (e) {
    wx.navigateTo({
      url: '/pages/mall/goodsDetail/goodsDetail?goodsId=' + e.currentTarget.dataset.goodsId
    })
  }
})